<!--3	季度交通违法情况通报-->
<template>
  <Layout>
    <Form ref="form1" :model="dataToQuery" :label-width="120">
      <Row class="query-form">
        <Col span="8">
          <FormItem label="年度：" prop="year">
            <DatePicker class="query-form-el" type="year" placeholder="请选择年度" v-model="dataToQuery.year1"
                        :clearable="false"
                        @on-change="()=>{if(dataToQuery.year1 instanceof Date){dataToQuery.year = dataToQuery.year1.getFullYear().toString()}}"></DatePicker>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="季度：" prop="quarter">
            <Select v-model="dataToQuery.quarter" placeholder="请选择季度">
              <Option v-for="(option, index) in quarterList" :value="option.value" :key="index">{{ option.label }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8" v-if="!switchFlag">
          <!--<Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>-->
          <Button @click="reset1" class="ivu-btn-reset">重置</Button>
          <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
        <Col span="8" v-else>
          <FormItem label="季度：" prop="quarter">
            <Select v-model="dataToQuery.quarter" placeholder="请选择季度">
              <Option v-for="(option, index) in quarterList" :value="option.value" :key="index">{{ option.label }}
              </Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8" offset="8">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
          <Button @click="reset1" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <!--   <Button size="large"  class="ivu-btn-add" icon="md-add"  @click="addInfo">新增</Button>
           <Button type="primary" class="ivu-btn-add"   icon="md-cloud-download"  @click="exportFormSubmit">导出</Button>-->
        </Col>
      </Row>
    </Form>
    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
           :loading='pageStatus.loading'
           border :columns="columns1" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
              show-elevator/>
      </Col>
    </Row>
    <Modal :title="this.getModalTitle('季度交通违法情况通报')" :transfer=false :mask-closable="false"
           v-model="dialogShow" v-if="dataToView && dialogShow" :width=800 :styles="{maxHeight:'700px'}"
           class-name='limit-height-dialog'>
      <Row>
        <Col span="24">
          <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':''" :show-message="false"
                :model="dataToView" :rules="mode === 'view'?{}:ruleCustom" :label-width="mode === 'view'?160:null"
                :label-position="mode === 'view'?'right':'top'">

            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='年份：' prop='yearDate'>
                  <div v-if="mode === 'view'">{{ dataToView.year }}</div>
                  <DatePicker v-else class="query-form-el" placeholder="年份" type="year"
                              v-model='dataToView.yearDate'></DatePicker>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="季度：" prop="quarter">
                  <div v-if="mode === 'view'">{{ dataToView.quarter }}</div>
                  <Select v-else v-model="dataToView.quarter" placeholder="请选择季度">
                    <Option v-for="(option, index) in quarterList" :value="option.value" :key="index">
                      {{ option.label }}
                    </Option>
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem v-if="mode === 'view'" label="通报附件：">
                  <div v-show="dataToView.idFiles.length>0" v-for="(item,index) in dataToView.idFiles">
                    <a @click="downloadFiles(item,index)"><span style="color: #3399ff;margin-left: 5px">{{
                        item.fileName
                      }}</span></a>
                    <Progress v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
                  </div>
                </FormItem>
                <FormItem v-else label="通报附件：" prop="idFiles">
                  <div>
                    <Upload ref="upload"
                            :before-upload="(file) => { beforeUpload1(file, 'id','violationNotification') }"
                            :show-upload-list="true"
                            :max-size="10240"
                            multiple
                            type="drag"
                            action="//jsonplaceholder.typicode.com/posts/">
                      <div style="padding: 10px">
                        <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                        <p>点击将文件拖拽到这里上传</p>
                        <!--<span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>-->
                      </div>
                    </Upload>
                  </div>
                  <div v-show="dataToView.idFiles.length>0" v-for="(item,index) in dataToView.idFiles" :key='item'>
                    <a @click="downloadFiles(item,index)">{{ item.fileName }}</a>
                    <Button type="text" icon="md-trash" @click="removeFile1(item.id, 'id','violationNotification')"
                            style="margin-left: 5px;margin-bottom: 3px"/>
                    <Progress v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
                    <!--<Progress  v-show="filePercentVisible[index]" :percent="filePercent[index]"></Progress>-->
                  </div>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='备注：' prop='notes'>
                  <div v-if="mode === 'view'">{{ dataToView.notes }}</div>
                  <Input v-else class='query-form-el' placeholder="请填写违法内容" type='textarea'
                         :autosize="{minRows:2,maxRows5}" v-model='dataToView.notes'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='填报人：' prop='createUserName'>
                  <div v-if="mode === 'view'">{{ dataToView.createUserName }}</div>
                  <Input v-else class='query-form-el' placeholder="请填写填报人" readonly type='text'
                         v-model='dataToView.createUserName'></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='填报时间：' prop='createDate'>
                  <div v-if="mode === 'view'">{{ renderViewDate(dataToView.createDate) }}</div>
                  <DatePicker v-else class="query-form-el" placeholder="请选择填报时间" readonly
                              v-model='dataToView.createDate'></DatePicker>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save' @click="submit('dialogForm')">确定</Button>
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
        <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
      </div>
    </Modal>
    <Modal title="季度交通违法情况通报" :transfer=false :mask-closable="false"
           v-model="dialogRecordShow"  :width=800 :styles="{maxHeight:'700px'}"
           class-name='limit-height-dialog'>
      <Form ref="form1datacopy" :model="form1datacopy" label-position="top">
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="12">
            <FormItem label="年份：" prop="year">
              <Input type="text" readonly v-model="form1datacopy.year"></Input>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="季度：" prop="quarter">
              <Input type="text" readonly v-model="form1datacopy.quarter"></Input>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="24">
            <FormItem label="附件：" prop="year">
              <div>
                <Upload ref="upload"
                        :before-upload="beforeUpload"
                        :show-upload-list="true"
                        :max-size="10240"
                        type="drag"
                        action="//jsonplaceholder.typicode.com/posts/">
                  <div style="padding: 10px">
                    <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                    <p>点击将文件拖拽到这里上传</p>
                    <span style="font-size:8px;color: #797a64">仅支持上传单个excel </span>
                  </div>
                </Upload>
              </div>
              <div v-if="fileTrue">
                <a>{{ file.name }}</a>
                <Button type="text" icon="md-trash" @click="deleteFile(file)" style="margin-left: 5px;margin-bottom: 3px"/>
              </div>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button type="primary" :loading="buttonLoading" class='ivu-btn-save'  @click="postFile">确定</Button>
        <Button type="primary" class='ivu-btn-cancel' @click="dialogRecordShow = false">取消</Button>
      </div>
    </Modal>
  </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import {formatDate} from '@/tools/index'

var cascaderDom = () => import('@/components/cascader-dom.vue');
import pageCommonFunction from '@/components/pageCommonFunction.js'
import {sessionStorage, cookie} from '@/common/cacheUtils.js';

export default {
  components: {cascaderDom},
  data() {
    return {
      ...this.createCommonDataField(),
      buttonLoading:false,
      dialogRecordShow:false,
      form1datacopy:{},
      columns1: [
        {title: '序号', width: 70, fixed: 'left', align: 'center', render: this.indexColumnsRender},
        {key: 'year', title: '年份', align: 'center', minWidth: 120,},
        {
          key: 'quarter', title: '季度', align: 'center', minWidth: 120, render: (h, params) => {
            return h('span', params.row.quarter + "季度");
          }
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            let flag = false;
            if(params.row.uploadList != undefined && params.row.uploadList.length > 0)
              flag = true;
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  color:!flag?'':'#c5c8ce',
                  pointerEvents:!flag?'':'none'
                },
                on: {
                  click: () => {
                    this.exportTemplateDatas(params.row.year, params.row.quarter);
                  }
                }
              }, '导出'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                },
                on: {
                  click: () => {
                    this.showRecordDialog(params.row);
                  }
                }
              }, '上传'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  color:flag?'':'#c5c8ce',
                  pointerEvents:flag?'':'none'
                },
                on: {
                  click: () => {
                    this.downloadFile(params.row);
                  }
                }
              }, '下载')
            ])
          }
        }
      ],
      ruleCustom: {
        yearDate: [{required: true, message: '请选择年份', trigger: 'change', type: 'date'}],
        quarter: [{required: true, message: '请选择季度', trigger: 'change',}],
        createUserName: [{required: true, message: '请填写填报人', trigger: 'change',}],
        createDate: [{required: true, message: '请填写填报时间', trigger: 'change', type: 'date'}],
        idFiles: [{
          validator: (rule, value, callback) => {
            if (this.dataToView.idFiles.length < 1) {
              callback('附件必须上传')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }]
      },
      fileTrue:false,
      file:{},
      currentRow:{},
      tableHeight: 10,
      dictMap: {},
      punishment: false,
      penaltyAmount: true,
      // api
      queryUrl: Api.trafficBreakRawListByTime,
      exportUrl: Api.exportSaTraff.replace('{{table}}', 'violationNotification'),
      deleteUrl: Api.deleteSaTraff.replace('{{table}}', 'violationNotification'),
      getUrl: Api.getSaTraff.replace('{{table}}', 'violationNotification'),
      updateUrl: Api.updateSaTraff.replace('{{table}}', 'violationNotification'),
      saveUrl: Api.saveSaTraff.replace('{{table}}', 'violationNotification'),
      uploadUrl: Api.uploadSaTraff.replace('{{table}}', 'violationNotification'),

      currentUser: JSON.parse(sessionStorage('userId').get('userId')),

      quarterList: [
        {value: '一', label: '一季度'},
        {value: '二', label: '二季度'},
        {value: '三', label: '三季度'},
        {value: '四', label: '四季度'}
      ],

    }
  },
  async mounted() {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 100;
    this.dataToQuery.year1 = new Date()
    this.dataToQuery.year = new Date().getFullYear().toString()
    this.query();
  },
  methods: {
    ...pageCommonFunction,
    beforeEditDialogOpen(data) {
      let year = data.row.year + '-01-01';
      data.row.yearDate = new Date(Date.parse(year.replace(/-/g, "/")));
    },
    deleteData(params) {
      this.deleteDateAjax(params);
    },
    reset1() {
      this.dataToQuery = {
        year1: new Date(),
        year: new Date().getFullYear().toString()
      };
      this.pagedata.currentPage = 1
      this.query()
    },
    query() {
      this.pageStatus.loading = true;
      let url = Api.trafficBreakRawListByTime;
      this.$http.get(url, {
        params: this.dataToQuery
      }).then((res) => {
        this.pageStatus.loading = false;
        this.dataTable = res.data.data.data;
        this.pagedata.total = res.data.data.totalSize;
        this.dataTable.forEach(item=>{
          this.getFile(item);
        })
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    submit(name) {
      if (this.dataToView.yearDate) {
        this.dataToView.year = this.dataToView.yearDate.getFullYear();
      }
      this.submitAjax(name);
    },
    showRecordDialog(item){
      this.dialogRecordShow = true;
      this.form1datacopy = item;
      this.fileTrue = false;
      this.currentRow = item;
      if(item.uploadList.length > 0){
        this.fileTrue = true;
        this.file = item.uploadList[0]
        this.file.name = this.file.fileName
      }
    },
    beforeUpload(file){
      if(this.fileTrue){
        this.$Message.error('已存在附件.');
        return false;
      }
      this.file = file;
      this.fileTrue = true
      return false;
    },
    getFile(item){
      var uploadImgUrl = Api.uploadPTWFiles + '/' + item.id + '/files/record';
      this.$http.get(uploadImgUrl, {
        params: {},
      }).then((res) => {
        if (res.data.result == "success") {
          this.$set(item,"uploadList",res.data.data);
        }
      })
    },
    deleteFile(){
      if(this.file.id != undefined) {
        let url = this.fileUrl + '/file/' + this.file.id;
        this.$http.delete(url).then((res) => {
          this.file = {}
          this.fileTrue = false;
        })
      }else{
        this.file = {}
        this.fileTrue = false;
      }
    },
    postFile(){
      if(this.fileTrue) {
        this.buttonLoading = true;
        let formData = new FormData();
        formData.append("files", this.file);
        this.$http.post(Api.uploadPTWFiles + '/' + this.currentRow.id + '/files/record', formData).then((res) => {
          if (res.data.result == "success") {
            this.$Message.success("保存成功");
            this.dialogRecordShow = false;
            this.buttonLoading  = false;
            this.getFile(this.currentRow);
          } else {
            this.$Message.error("附件上传失败");
            this.dialogRecordShow = false;
            this.buttonLoading = false;
          }
        }).catch(e => {
          console.log(e);
          this.$Message.error("附件上传失败");
        })
      }else{
        this.dialogRecordShow = false;
        this.$set(this.currentRow,"uploadList",[]);
      }
    },
    downloadFile(item){
      if(item.uploadList.length > 0) {
        this.$http.get(Api.uploadPTWFiles + '/file/' + item.uploadList[0].id, {
          responseType: 'blob'      //告诉服务器我们需要的响应格式
        }).then((res) => {
          const aLink = document.createElement("a");
          let blob = new Blob([res.data], {
            type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
          });
          aLink.href = URL.createObjectURL(blob)
          aLink.download = item.uploadList[0].fileName //标题
          aLink.click()
          document.body.appendChild(aLink)
        })
      }
    },
    exportTemplateDatas(year, quarter) {
      let data = {
        year: year,
        quarter: quarter
      };
      let _this = this;
      this.buttonLoading = true;
      let url = Api.exportTrafficWord;
      this.$http.get(url, {
        params: data, responseType: 'blob',
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.body.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = "金隅交安办字〔" + year + "〕-" + year + "年" + quarter + "季度集团交通违法情况通报.doc" //标题
        aLink.click()
        this.buttonLoading = false;
        this.exportModal = false;
        document.body.appendChild(aLink)
      })
    },
    createEmptyDataToAdd() {
      return {
        createDate: new Date(),
        createUserId: this.currentUser.userId,
        createUserName: this.currentUser.userName,
        id: this.get_uuid(),
        idFiles: [],

      }
    },
    async afterDataToViewInit() {
      await this.getFiles1('id', 'violationNotification');
    },
  },
  watch: {},
}
</script>

<style lang='css' scoped>
.ivu-form-item {
  padding-right: 20px;
}

.query-form-el, .ivu-date-picker, .ivu-input-wrapper {
  width: 100%;
}

</style>
